const config = require("../config");
const ss = require("socket.io-stream");
const fs = require("fs");
const path = require("path");

sockets = {
  io: null,
  createSockerServer: (server, httpServer) => {
    process.setMaxListeners(0);
    sockets.io = new server(httpServer, {
      cors: {
        origin: config.origins,
        credentials: true,
      },
    });
  },
  connect: () => {
    sockets.io.on("connection", (socket) => {
      // console.log("服务端链接成功", socket.id);
      ss(socket).on("private message", async (stream, data) => {
        var filename = path.basename(data.name);
        var wd = fs.createWriteStream(filename);
        stream.pipe(wd);
        wd.once("close", function () {
          fs.readFile(
            path.resolve(__dirname, "../" + filename),
            (err, buffer) => {
              socket.broadcast.emit(data.channel, {
                msg: buffer,
                fromUser: data.fromUser,
                isImg: data.isImg,
                isVideo: data.isVideo,
                isAudio: data.isAudio,
                voiceDuration: data.voiceDuration,
              });
              fs.unlink(path.resolve(__dirname, "../" + filename),(err)=>{
              })
            }
          );
        });
      });
      // 除视频外的私聊
      socket.on("private message", async ( data) => {
              socket.broadcast.emit(data.channel, {
                msg: data.msg,
                fromUser: data.fromUser,
                isImg: data.isImg,
                isAudio: data.isAudio,
                voiceDuration: data.voiceDuration,
              });
      });
      sockets.disconnect(socket);
    });
  },
  disconnect: (socket) => {
    socket.on("disconnect", () => {
      // console.log("服务端断开链接成功",socket.id);
      // socket.on("private message", (data) => {
      //   console.log("收到", data.channel);
      //   socket.broadcast.emit(data.channel, {
      //     msg: data.msg,
      //     fromUser: data.fromUser,
      //   });
      // });
    });
  },
};

module.exports = sockets;
